package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        // 非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())
         || StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getNickname())
        || StringUtil.isEmpty(user.getSalt())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 按照用户名查询用户是否存在
        User existsUser = userMapper.selectByUserName(user.getUsername());
        if (existsUser != null) {
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 新增用户
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);

        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        int row = userMapper.insertSelective(user);
        if (row != 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        log.info("新增用户成功 username:{}", user.getUsername());

    }

    @Override
    public User selectByUserName(String username) {
        if (StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        // 非空校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 按照用户名查询用户
        User user = userMapper.selectByUserName(username);
        // 查询结果非空校验
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + " username:{}", username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 校验密码
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + ",密码错误， username:{}", username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        log.info("用户登录成功， username:{}", username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id == null || id <= 0) {
            log.warn (ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 当前用户查询不存在
            log.warn(ResultCode.ERROR_IS_NULL.toString() + " userId: " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL ));
        }
        // 增加用户发帖的数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);

        // 更新数据库
        int row  = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1 ");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn (ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 当前板块查询不存在
            log.warn(ResultCode.ERROR_IS_NULL.toString() + " user Id: " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 减少帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);

        if (updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }

        // 更新数据库
        int row  = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1 ");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public void modifyInfo(User user) {
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 定义一个标准位，校验所有参数是否为空
        boolean flag = false;
        // 对每个参数进行校验，并处理

        // 定义一个更新对象，防止用户传入的User对象设置了其他的属性，当使用动态sql时，覆盖没有更新的字段
        User updateUser = new User();
        updateUser.setId(user.getId());

        // 用户名
        if (!StringUtil.isEmpty(user.getUsername())
        && !user.getUsername().equals(existsUser.getUsername())) {
            // 用户名不为空，且与之前的用户名不一致
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null) {
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            // 没有找到相应的用户，用户名被修改
            updateUser.setUsername(user.getUsername());
            flag = true;
        }

        // 昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            // 昵称不为空，且与之前的昵称不一致
            updateUser.setNickname(user.getNickname());
            flag = true;
        }

        // 性别
        if (user.getGender() != null && !user.getGender().equals(existsUser.getGender())) {
            // 性别不为空，且与之前的性别不一致
            updateUser.setGender(user.getGender());
            if (user.getGender() > 2 || user.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            flag = true;
        }

        // 邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                &&!user.getEmail().equals(existsUser.getEmail())) {
            // 邮箱不为空，且与之前的邮箱不一致
            updateUser.setEmail(user.getEmail());
            flag = true;
        }

        // 手机号
        if (!StringUtil.isEmpty(user.getPhoneNum())
                &&!user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            // 手机号不为空，且与之前的手机号不一致
            updateUser.setPhoneNum(user.getPhoneNum());
            flag = true;
        }

        // 个人简介
        if (!StringUtil.isEmpty(user.getRemark()) &&
                !user.getRemark().equals(existsUser.getRemark())) {
            // 个人简介不为空，且与之前的个人简介不一致
            updateUser.setRemark(user.getRemark());
            flag = true;
        }

        // 根据标志位判断是否可以更新
        if (flag) {
            int row = userMapper.updateByPrimaryKeySelective(updateUser);
            if (row!= 1) {
                log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1 ");
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
            }
        } else {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword)
                || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 校验旧密码是否正确
        String encryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

        // 密码修改
        String salt = UUIDUtil.uuid_32();
        // 新密码密文
        String newEncryptPassword = MD5Util.md5Salt(newPassword, salt);
        // 构建更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(newEncryptPassword);
        Date date = new Date();
        updateUser.setUpdateTime(date);

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row!= 1) {
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1 ");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
